package com.ideal.hadoopadmin.web.controller.webapi;

import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.api.tools.Tool;
import com.ideal.hadoopadmin.common.entity.Result;
import com.ideal.hadoopadmin.entity.cluster.ClusterUser;
import com.ideal.hadoopadmin.entity.cluster.user.*;
import com.ideal.hadoopadmin.entity.cluster.user.Queue;
import com.ideal.hadoopadmin.entity.main.User;
import com.ideal.hadoopadmin.entity.system.Role;
import com.ideal.hadoopadmin.entity.system.UserRole;
import com.ideal.hadoopadmin.entity.system.company.SystemCompany;
import com.ideal.hadoopadmin.framework.message.WebMessageLevel;
import com.ideal.hadoopadmin.framework.web.json.JsonObject;
import com.ideal.hadoopadmin.service.cluster.ClusterUserService;
import com.ideal.hadoopadmin.service.cluster.user.KbrconfigService;
import com.ideal.hadoopadmin.service.main.SystemUserService;
import com.ideal.hadoopadmin.service.system.RoleService;
import com.ideal.hadoopadmin.service.system.UserRoleService;
import com.ideal.hadoopadmin.service.system.company.SystemCompanyService;
import com.ideal.hadoopadmin.web.controller.UIController;
import com.ideal.hadoopadmin.web.controller.cluster.ClusterUserController;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *
 */
@Controller
@RequestMapping(ClusterUserAPI.PORTAL_PREFIX)
public class ClusterUserAPI extends UIController {
    private static final Integer DEFAULT_LENGTH = 20;//参数数组长度默认20
    private static final Long COMPANY_ID = 0L;//默认电信id
    private static final String CONTACT_PERSON = "yuanying";
    private static final String PHONE_NUMBER = "18516262844";
    private static final String EMAIL = "idea@cn.com";
    private static final String REMARK = "meppo调用接口";
    private static final Long USERTYPE_ID = 2L;//默认内部用户
    private static final Long CLUSTERTYPE_ID = 1L;///默认为正式集群
    private static final Long VALIDDAY = 0l;//默认为0 status 默认开启
    private static final String QUEUE_NAME = "";
    private static final Long MIN_RESOURCE = 0l;
    private static final Long MAX_RESOURCE = 0L;
    private static final Long MAX_APP = 0L;
    private static final Float WEIGHT = 0F;
    private static final String ACL = "";
    private static final Long MIN_CPU = 0L;
    private static final Long MAX_CPU = 0L;
    @Resource
    private ClusterUserService clusterUserService;
    @Resource
    private KbrconfigService kbrconfigService;
    @Override
    public String getPortalPrefix() {
        return PORTAL_PREFIX;
    }

    Logger logger = LoggerFactory.getLogger(ClusterUserAPI.class);
    public final static String PORTAL_PREFIX = "/webapi/user";
    //无序号的不需要传递,按照序号以逗号隔开进行字符串拼接传过来
    //集合单个以分号给开,如下所示.如 paramQueueList = "paraQueue1;paramQueue2;paramQueue3";
    //如果某一个参数里面本身就是包括多个,如machineIds,传值时可以另外的符号,如空格 machineIds = "1 2 3 4";
    //除了接口需要,另外的参数都可以不传,直接给默认值
    //paramUser = id,0 userName,1 clientPW,systemPW,2 companyId(默认公司电信),3 contactPerson,4 phoneNumber,5 email,6 remark,7 userTypeId,status,8 clusterTypeId,changeTime,createTime
    //paramHdfs = id,userId,0 hdfsSpace,1 hdfsFileCount,2 hdfsSpaceUnit,hdfsPath
    //paramKbr = id,userId,0 validDay,1 machineIds,2 status,changeTime,createTime,startTime,endTime
    //paramQueue = id,userId,0 queueName,1 minResource,2 maxResource,3 maxApp,4 weight,5 acl,6 minCpu,7 maxCpu,modifyTime
    @RequestMapping("save_user")
    @ResponseBody
    public JsonObject save(String paramUser,String paramHdfs,String paramKbr,String paramQueueList) {
        //进行参数转换
        ClusterUser clusterUser = getClusterUser(paramUser);
        Hdfsquota hdfsquota = getHdfs(paramHdfs);
        if(hdfsquota!=null){
            hdfsquota.setHdfsPath("/user/" + clusterUser.getUserName());
        }
        Kbrconfig kbrconfig = getKbr(paramKbr);
        List<Queue> queues = getQueues(paramQueueList);
        clusterUserService.saveCluserUser(clusterUser,hdfsquota,kbrconfig,queues,null);
//        Map<String,Object> map = getSaveUserParam(paramUser,paramHdfs,paramKbr,paramQueueList);
//        //获取返回结果
//        clusterUserService.saveCluserUser((ClusterUser)map.get("clusterUser"),(Hdfsquota)map.get("hdfs"),(Kbrconfig)map.get("kbrconfig"),(List<Queue>)map.get("queueList"));
        return JsonObject.alert("用户名已存在！", WebMessageLevel.WARN);
    }

    @RequestMapping("update_user")
    @ResponseBody
    public JsonObject updateUser(String paramUser){
        ClusterUser clusterUser = getClusterUser(paramUser);
        clusterUserService.updateClusterUser(clusterUser);
        return JsonObject.alert("修改用户成功", WebMessageLevel.SUCCESS);
    }
    //修改时,如果参数不传,相当于修改成默认值
    @RequestMapping("update_kbr")
    @ResponseBody
    public JsonObject updateKbr(String paramKbr){
        Kbrconfig kbrconfig = getKbr(paramKbr);
        Result result = new Result();
        kbrconfigService.callKDCAPI(kbrconfig);
        //根据返回结果判断是否要入库
        kbrconfigService.updateByUserId(kbrconfig);
        return JsonObject.alert("修改用户成功", WebMessageLevel.SUCCESS);
    }
    @RequestMapping("update_hdfs")
    @ResponseBody
    public JsonObject updateHdfs(String paramHdfs){
        Hdfsquota hdfsquota = getHdfs(paramHdfs);
        ClusterUser clusterUser = clusterUserService.queryClusterUserById(hdfsquota.getUserId());
        if(hdfsquota!=null){
            hdfsquota.setHdfsPath("/user/" + clusterUser.getUserName());
        }
        return JsonObject.alert("修改HDFS成功", WebMessageLevel.SUCCESS);
    }
    //删除租户param=#{id},id为数字
    @RequestMapping("delete_clusterUser")
    @ResponseBody
    public JsonObject deleteClusterUser(String param) {
        Long id = Long.parseLong(param);
        String message = clusterUserService.deleteClusterUserById(id);
        if ("success".equals(message)) {
            return JsonObject.alert("用户删除成功", WebMessageLevel.SUCCESS);
        } else {
            return JsonObject.alert("用户删除失败", WebMessageLevel.ERROR);
        }
    }
    //增加数组长度
    public String[] arrayAddLength(String[] arr,Integer newLength){
        String [] newArr = new String[newLength];
        System.arraycopy(arr,0,newArr,0,arr.length);
        return newArr;
    }
    /*****************************************************************************************/

    //9 id,0 userName,1 clientPW,systemPW,2 companyId,3 contactPerson,4 phoneNumber,5 email,6 remark,7 userTypeId,status,8 clusterTypeId,changeTime,createTime
    // userName,clientPW,systemPW 必传,另外的不传直接给默认值
    //进行修改时才传入id
    private ClusterUser getClusterUser(String paraUser){
        String [] user = arrayAddLength(paraUser.split(","),DEFAULT_LENGTH);
        ClusterUser clusterUser = new ClusterUser();
        clusterUser.setUserName(user[0]);
        clusterUser.setClientPW(user[1]);
        clusterUser.setSystemPW(Tool.GeneratRandomPW());
        if(StringUtils.isBlank(user[2])){
            clusterUser.setCompanyId(COMPANY_ID);//默认电信
        }else {
            clusterUser.setCompanyId(Long.parseLong(user[2]));
        }
        if(StringUtils.isBlank(user[3])){
            clusterUser.setContactPerson(CONTACT_PERSON);
        }else {
            clusterUser.setContactPerson(user[3]);
        }
        if(StringUtils.isBlank(user[4])){
            clusterUser.setPhoneNumber(PHONE_NUMBER);
        }else {
            clusterUser.setPhoneNumber(user[4]);
        }
        if(StringUtils.isBlank(user[5])){
            clusterUser.setEmail(EMAIL);
        }else {
            clusterUser.setEmail(user[5]);
        }
        if(StringUtils.isBlank(user[6])){
            clusterUser.setRemark(REMARK);
        }else {
            clusterUser.setRemark(user[6]);
        }
        if(StringUtils.isBlank(user[7])){
            clusterUser.setUserTypeId(USERTYPE_ID);
        }else {
            clusterUser.setUserTypeId(Long.parseLong(user[7]));
        }
        if(StringUtils.isBlank(user[8])){
            clusterUser.setClusterTypeId(CLUSTERTYPE_ID);
        }else {
            clusterUser.setClusterTypeId(Long.parseLong(user[8]));
        }
        if(StringUtils.isNotBlank(user[9])){
            clusterUser.setId(Long.parseLong(user[9]));
        }
        clusterUser.setStatus(ClusterUser.onStatus);//新建时默认为有效
        clusterUser.setCreateTime(System.currentTimeMillis());
        clusterUser.setChangeTime(System.currentTimeMillis());
        return clusterUser;
    }
    //3 id,4 userId,0 hdfsSpace,1 hdfsFileCount,2 hdfsSpaceUnit,hdfsPath
    //id和userId在修改时才传入
    private Hdfsquota getHdfs(String paramHdfs){
        String[] hdfs = arrayAddLength(paramHdfs.split(","),DEFAULT_LENGTH);
        Hdfsquota hdfsquota = null;//hdfsSpace,hdfsFileCount,都不为空时,hdfsquota才进行配置
        if (StringUtils.isNotBlank(hdfs[0])&& StringUtils.isNotBlank(hdfs[1])){
            hdfsquota.setHdfsPath(hdfs[0]);
            hdfsquota.setHdfsFileCount(Integer.parseInt(hdfs[1]));
            hdfsquota.setHdfsSpaceUnit(hdfs[2]);
            if(StringUtils.isNotBlank(hdfs[3])){
                hdfsquota.setId(Long.parseLong(hdfs[3]));
            }
            if(StringUtils.isNotBlank(hdfs[4])){

            }
        }
        return hdfsquota;
    }
    //3 id,4 userId,0 machineIds,1 validDay,2 status,changeTime,createTime,startTime,endTime
    //machineIds 必须传入,id和userId在修改时才传入
    private Kbrconfig getKbr(String paramKbr){
        String[] kbr = arrayAddLength(paramKbr.split(","),DEFAULT_LENGTH);
        Kbrconfig kbrconfig = new Kbrconfig();
        String machineIds = kbr[0].trim().replaceAll(" ", ",");//暂定空格,以后再改
        kbrconfig.setMachineIds(machineIds);
        //将valiDay添加至kbrconfig里面
        if (StringUtils.isBlank(kbr[1])) {
            kbrconfig.setValidDay(VALIDDAY);
        } else {
            kbrconfig.setValidDay(Long.parseLong(kbr[1]));
        }
        if(StringUtils.isBlank(kbr[2])){
            kbrconfig.setStatus(Kbrconfig.onStatus);//开启
        }else {
            kbrconfig.setStatus(Integer.parseInt(kbr[2]));
        }
        if(StringUtils.isNotBlank(kbr[3])){
            kbrconfig.setId(Long.parseLong(kbr[3]));
        }
        if(StringUtils.isNotBlank(kbr[4])){
            kbrconfig.setUserId(Long.parseLong(kbr[4]));
        }
        kbrconfig.setCreateTime(System.currentTimeMillis());
        kbrconfig.setChangeTime(System.currentTimeMillis());
        kbrconfig.setStartTime(System.currentTimeMillis());
        //当前时间加上有效期
        Long endTime = kbrconfig.getStartTime()+kbrconfig.getValidDay()*24*60*60*1000;
        kbrconfig.setEndTime(endTime);
        return kbrconfig;
    }
    private List<Queue> getQueues(String paramQueueList){
        List<Queue> queueList = new ArrayList<Queue>();
        String [] queues = paramQueueList.split(";");//以分号隔开每一个queue
        for(int i=0;i<queues.length;i++){
            Queue queue = getQueue(queues[i]);
            queueList.add(queue);
        }
        return queueList;
    }
    //8 id,9 userId,0 queueName,1 minResource,2 maxResource,3 maxApp,4 weight,5 acl,6 minCpu,7 maxCpu,modifyTime
    //无必传值,id和userId在修改时才传入
    private Queue getQueue(String paraQueue){
        String[] squeue = arrayAddLength(paraQueue.split(","),DEFAULT_LENGTH);
        Queue queue = new Queue();
        if(StringUtils.isBlank(squeue[0])){
            queue.setQueueName(QUEUE_NAME);
        }else {
            queue.setQueueName(squeue[0]);
        }
        if(StringUtils.isBlank(squeue[1])){
            queue.setMinResource(MIN_RESOURCE);
        }else {
            queue.setMinResource(Long.parseLong(squeue[1]));
        }
        if(StringUtils.isBlank(squeue[2])){
            queue.setMaxResource(MAX_RESOURCE);
        }else {
            queue.setMaxResource(Long.parseLong(squeue[2]));
        }
        if(StringUtils.isBlank(squeue[3])){
            queue.setMaxApp(MAX_APP);
        }else {
            queue.setMaxApp(Long.parseLong(squeue[3]));
        }
        if(StringUtils.isBlank(squeue[4])){
            queue.setWeight(WEIGHT);
        }else {
            queue.setWeight(Float.parseFloat(squeue[4]));
        }
        if(StringUtils.isBlank(squeue[5])){
            queue.setAcl(ACL);
        }else {
            queue.setAcl(squeue[5]);
        }
        if(StringUtils.isBlank(squeue[6])){
            queue.setMinCpu(MIN_CPU);
        }else {
            queue.setMinCpu(Long.parseLong(squeue[6]));
        }
        if(StringUtils.isBlank(squeue[7])){
            queue.setMaxCpu(MAX_CPU);
        }else {
            queue.setMaxCpu(Long.parseLong(squeue[7]));
        }
        if(StringUtils.isNotBlank(squeue[8])){
            queue.setId(Long.parseLong(squeue[8]));
        }
        if(StringUtils.isNotBlank(squeue[9])){
            queue.setUserId(Long.parseLong(squeue[9]));
        }
        queue.setModifyTime(System.currentTimeMillis());
        return queue;
    }
    //paramUser = id,0 userName,1 clientPW,systemPW,2 companyId(默认公司电信),3 contactPerson,4 phoneNumber,5 email,6 remark,7 userTypeId,status,8 clusterTypeId,changeTime,createTime
    //paramHdfs = id,userId,0 hdfsSpace,1 hdfsFileCount,2 hdfsSpaceUnit,hdfsPath
    //paramKbr = 3 id,4 userId,0 machineIds,1 validDay,2 status,changeTime,createTime,startTime,endTime
    //paramQueue = id,userId,0 queueName,1 minResource,2 maxResource,3 maxApp,4 weight,5 acl,6 minCpu,7 maxCpu,modifyTime
    public static  void main(String[] args){
        ClusterUserAPI clusterUserAPI = new ClusterUserAPI();
        String paramUser = "yuanying,123qwe@";
        String paramKbr = "56 119";
        String paramHdfs = "";
        String paramQueueList = "";
        clusterUserAPI.save(paramUser,paramHdfs,paramKbr,paramQueueList);
    }

}
